#ifndef STREAMBUFFER_HPP
#define STREAMBUFFER_HPP
#include <cstring>
#include <cstdlib>
using std::realloc;
using std::malloc;
using std::memcpy;

struct StreamBuffer
{
public:
	StreamBuffer();
	~StreamBuffer();
	
	void append(int len, const char *data);
	void popFront(int len);
	void clear();
	
	void *reserveSpace(int len);
	void appendReserved(int len);
	
	inline void appendByte(char ch)
	{
		if(len < alloc) {
			data[len++] = ch;
		} else {
			append(1, &ch);
		}
	}
	
	inline void set(int len, const char *newData)
	{
		if(len > alloc) {
			do {
				alloc *= 2;
			} while(len > alloc);
			data = (char*)realloc(data, alloc);
		}
		memcpy(data, newData, len);
		this->len = len;
	}
	
	inline const char *getData() const { return data; }
	inline int getLen() const { return len; }
	
private:
	StreamBuffer(const StreamBuffer &copy);
	char *data;
	int len;
	int alloc;
};

#endif
